package com.yuezhu.citylist;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yuezhu.R;
import com.yuezhu.activity.MyprojectActivity;
import com.yuezhu.global.BaseActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 城市选择
 *
 * @author gugalor
 */
public class CityListActivity extends BaseActivity {
    @InjectView(R.id.iv_menu)
    ImageView ivMenu;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.iv_quite)
    ImageView ivQuite;
    @InjectView(R.id.city_name)
    AutoCompleteTextView cityName;
    private BaseAdapter adapter;
    private ListView mCityLit;
    private TextView overlay, citysearch;
    private Button backbutton;
    private MyLetterListView letterListView;
    private HashMap<String, Integer> alphaIndexer;
    private String[] sections;
    private Handler handler;
    private OverlayThread overlayThread;
    private SQLiteDatabase database;
    private ArrayList<CityModel> mCityNames;
    private View city_locating_state;
    private TextView city_locate_state;
    private String location_city;
    private ImageButton title_left_btn;
    // title 控件
    private TextView title_bac, title_text, title_yes;
    View hotcityall;

    String[] hotcity = new String[]{"北京", "上海", "广州", "深圳", "杭州", "南京"};
    WindowManager windowManager;
    private AlertDialog dialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final LayoutInflater localLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View city_layout = localLayoutInflater.inflate(R.layout.public_cityhot,
                null);
        setContentView(city_layout);
        ButterKnife.inject(this);
        ivMenu.setImageResource(R.drawable.back_icon);
        ivMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ivQuite.setVisibility(View.INVISIBLE);
        tvTitle.setText("城市列表");
        // 初始化title
        initTitle();
        initview(city_layout);
        /**
         * 初始化定位城市
         */
        initLocationCity(localLayoutInflater);
        /**
         * 初始化常用城市
         */
//        initCommenUsed(localLayoutInflater);
        setListener();
        mCityNames = MyprojectActivity.mCityModels;
        alphaIndexer = new HashMap<String, Integer>();
        handler = new Handler();
        overlayThread = new OverlayThread();
        initOverlay();
        /**
         * 设置城市列表数据
         */
        setAdapter(mCityNames);
    }


    private void setListener() {


        mCityLit.setOnItemClickListener(new CityListOnItemClick());


        letterListView
                .setOnTouchingLetterChangedListener(new LetterListViewListener());
    }

    private void initCommenUsed(LayoutInflater localLayoutInflater) {
        // 常用城市
        View hotheadview = localLayoutInflater.inflate(
                R.layout.public_cityhot_header_padding, mCityLit, false);
        mCityLit.addHeaderView(hotheadview, null, false);
        hotcityall = localLayoutInflater.inflate(
                R.layout.public_cityhot_allcity, mCityLit, false);
        final GridView localGridView = (GridView) hotcityall
                .findViewById(R.id.public_hotcity_list);

        mCityLit.addHeaderView(hotcityall);

        HotCityGridAdapter adapter = new HotCityGridAdapter(this, hotCityList);
        localGridView.setAdapter(adapter);
        localGridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String cityModel = parent.getAdapter().getItem(position)
                        .toString();
                Intent intent = new Intent();
                intent.putExtra("city", cityModel);
                setResult(2, intent);
                finish();
            }
        });
    }

    private void initLocationCity(LayoutInflater localLayoutInflater) {

    }

    private void initview(View city_layout) {
        // 搜索按钮
        citysearch = (TextView) city_layout
                .findViewById(R.id.city_search_edittext);
        // 城市listview
        mCityLit = (ListView) city_layout
                .findViewById(R.id.public_allcity_list);
        // 字母listview
        letterListView = (MyLetterListView) city_layout
                .findViewById(R.id.cityLetterListView);
    }

    private void initTitle() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    /**
     * @return
     */
    private ArrayList<CityModel> getCityNames() {
        DBManager dbManager = new DBManager(this);
        dbManager.openDateBase();
        dbManager.closeDatabase();
        database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
                + DBManager.DB_NAME, null);
        ArrayList<CityModel> names = new ArrayList<CityModel>();
        Cursor cursor = database.rawQuery(
                "SELECT * FROM T_City ORDER BY NameSort", null);
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);
            CityModel cityModel = new CityModel();
            cityModel.setName(cursor.getString(cursor
                    .getColumnIndex("CityName")));
            cityModel.setShouzimu(cursor.getString(cursor
                    .getColumnIndex("NameSort")));
            if (cityModel.getName().length() <= "阿拉蒙山".length()) {
                names.add(cityModel);
                if (cityModel.getName().equals("承德")) {
                    cityModel = new CityModel("长春", "C");
                    names.add(cityModel);
                    cityModel = new CityModel("长沙", "C");
                    names.add(cityModel);
                }
            }
        }
        cursor.close();
        database.close();
        return names;
    }

    /**
     * б 1/4
     *
     * @author
     */
    class CityListOnItemClick implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                                long arg3) {
            CityModel cityModel = (CityModel) mCityLit.getAdapter()
                    .getItem(pos);
            if (cityModel != null) {
                String cityName = cityModel.getName();

                finish();

            }
        }

    }

    /**
     * ListView
     *
     * @param list
     */
    private void setAdapter(final List<CityModel> list) {
        if (list != null) {
            ArrayAdapter<CityModel> adapter1 = new ArrayAdapter<CityModel>(CityListActivity.this,
                    R.layout.simple_dropdown_item_1line, list);
            cityName.setAdapter(adapter1);
            cityName.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    TextView textView = (TextView) view;
                    String name = textView.getText().toString();
                    CityModel cityModel = null;
                    for (CityModel model : mCityNames) {
                        if (model.getName().equalsIgnoreCase(name)) {
                            cityModel = model;
                            break;
                        }
                    }
                    if (cityModel == null) {
                        return;
                    }
                    Intent intent = new Intent();
                    intent.putExtra("city", cityModel.getName());
                    intent.putExtra("id", cityModel.getId());
                    setResult(1, intent);
                    finish();
                }
            });
            adapter = new ListAdapter(this, list);
            mCityLit.setAdapter(adapter);
        }
    }

    private Map<String, List<String>> cityMap = new HashMap<String, List<String>>();
    private List<String> hotCityList = new ArrayList<String>();

    /**
     * ListViewAdapter
     *
     * @author gugalor
     */
    private class ListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private List<CityModel> list;
        private List<String> cityKeyList = new ArrayList<String>();

        public ListAdapter(Context context, List<CityModel> list) {

            this.inflater = LayoutInflater.from(context);
            this.list = list;
            alphaIndexer = new HashMap<String, Integer>();

            for (int i = 0; i < list.size(); i++) {

                //
                // getAlpha(list.get(i));
                String currentStr = list.get(i).getShouzimu();

                List<String> mycityList = cityMap.get(currentStr);
                if (mycityList == null) {
                    mycityList = new ArrayList<String>();
                }
                mycityList.add(list.get(i).getName());
                cityMap.put(currentStr, mycityList);

                if (!cityKeyList.contains(currentStr)) {
                    cityKeyList.add(currentStr);
                }
            }
            cityKeyList.remove("");
            Collections.sort(cityKeyList);
            sections = new String[cityKeyList.size()];
            for (int j = 0; j < cityKeyList.size(); j++) {
                String currentStr = cityKeyList.get(j);
                //
                String previewStr = (j - 1) >= 0 ? cityKeyList.get(j - 1) : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = cityKeyList.get(j);
                    alphaIndexer.put(name, j);
                    sections[j] = name;
                }
            }
        }

        @Override
        public int getCount() {
            return cityKeyList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.public_cityhot_item,
                        null);
                holder = new ViewHolder();
                holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
                holder.name = (TextView) convertView
                        .findViewById(R.id.public_cityhot_item_textview);
                holder.gridView = (MyGridView) convertView
                        .findViewById(R.id.public_city_list);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            // holder.name.setText(list.get(position).getName());
            holder.name.setVisibility(View.GONE);
            String currentStr = cityKeyList.get(position);
            String previewStr = (position - 1) >= 0 ? cityKeyList
                    .get(position - 1) : " ";
            if (!previewStr.equals(currentStr)) {
                holder.alpha.setVisibility(View.VISIBLE);
                holder.alpha.setText(currentStr);
                holder.gridView.setVisibility(View.VISIBLE);
                List<String> citylist1 = cityMap.get(currentStr);
                HotCityGridAdapter adapter = new HotCityGridAdapter(
                        CityListActivity.this, citylist1);
                holder.gridView.setAdapter(adapter);
                holder.gridView
                        .setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent,
                                                    View view, int position, long id) {
                                String cityModel = parent.getAdapter()
                                        .getItem(position).toString();
                                Intent intent = new Intent();
                                intent.putExtra("city", cityModel);
                                for (CityModel model : mCityNames) {
                                    if (model.getName().equalsIgnoreCase(cityModel)) {
                                        intent.putExtra("id", model.getId());
                                        break;
                                    }
                                }
//								MyToast.showDefaltToast(cityModel+"");
                                setResult(1, intent);
                                finish();
                            }
                        });
            } else {
                holder.alpha.setVisibility(View.GONE);
                holder.gridView.setVisibility(View.GONE);
            }
            return convertView;
        }

        private class ViewHolder {
            TextView alpha;
            TextView name;
            MyGridView gridView;
        }

    }

    // ’
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    @Override
    protected void onDestroy() {
        windowManager.removeView(overlay);
        super.onDestroy();
    }

    private class LetterListViewListener implements
            MyLetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s);
                int position1 = position;
                mCityLit.setSelection(position1);
                overlay.setText(sections[position]);
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // Уoverlay
                handler.postDelayed(overlayThread, 1500);
            }
        }

    }

    // overlay
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();

    }

}